/**
 * 2009-10-26 下午05:50:29 
 * esignature
 * com.smc.dao.impl
 * UserDaoImpl
 */
package com.smc.dao.impl;

import java.sql.Date;
import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;

import com.smc.dao.UserDao;
import com.smc.domain.model.Authentication;
import com.smc.domain.model.Hospital;
import com.smc.domain.model.User;

/**
 * @author chenheng
 * @version 0.0.1
 * 持久层用户接口实现
 */
public class UserDaoImpl extends HibernateDaoSupport implements UserDao {

	
	public void save_HO_US_SA_user(User user) {
		getHibernateTemplate().saveOrUpdate(user);
	}

	public List<Authentication> fetch_IG_IG_IG_authentication(User user) {
		return null;
	}
	@SuppressWarnings("unchecked")
	public User login_IG_IG_IG_user(String username, String password) {
		String hql = "SELECT a FROM User a WHERE a.username=? AND a.password=?";
		String[] params = new String[]{username,password}; 
		List<User> ul = getHibernateTemplate().find(hql, params);
		User user = null ;
		if (ul.size() > 0) {
			user = ul.iterator().next();
		}
		return user ;
	}

	@SuppressWarnings("unchecked")
	public List<User> fetch_OP_US_FE_user(String hospitalUuid) {
		Object hospital = getHibernateTemplate().load(Hospital.class, hospitalUuid);
		String hql = "SELECT new User(uuid,username) FROM User u WHERE u.hospital = ?";
		List<User> lu = getHibernateTemplate().find(hql, hospital);
		return lu;
	}

	public void saveUser(User user) {
		Date date = new Date(System.currentTimeMillis());
		user.setRegisterTime(date);
		getHibernateTemplate().saveOrUpdate(user);
	}

	@SuppressWarnings("unchecked")
	public List<User> fetchVerifiedUser(boolean verified, int pageIndex, int pageSize) {
		Session session = getSession();
		String hql = "FROM User u JOIN FETCH u.hospital WHERE u.verified = ?";
		Query query = session.createQuery(hql);
		query.setParameter(0, verified);
		query.setFirstResult((pageIndex-1)*pageSize);
		query.setMaxResults(pageSize);
		return query.list();
	}

	public int countVerifiedUser(boolean verified) {
		int count = 0 ;
		String hql = "SELECT COUNT(a) FROM User a WHERE a.verified = ? ";
		List l = getHibernateTemplate().find(hql, verified);
		if ( l.size() > 0 ) {
			count = ((Long) l.iterator().next()).intValue() ;
		}
		return count;
	}

	public int countUser() {
		int count = 0 ;
		String hql = "SELECT COUNT(a) FROM User a ";
		List l = getHibernateTemplate().find(hql);
		if ( l.size() > 0 ) {
			count = ((Long) l.iterator().next()).intValue();
		}
		return count;
	}

	@SuppressWarnings("unchecked")
	public List<User> fetchUser(int pageIndex, int pageSize) {
		Session session = getSession();
		String hql = "FROM User u JOIN FETCH u.hospital";
		Query query = session.createQuery(hql);
		query.setFirstResult((pageIndex-1)*pageSize);
		query.setMaxResults(pageSize);
		return query.list();
	}

	public int countSearchUser(String firstName, String lastName) {
		int count = 0 ;
		StringBuffer sb = new StringBuffer();
		sb.append("SELECT COUNT(a) FROM User a WHERE 1 = 1 ");
		if ( null != firstName && ! "".equals(firstName.trim())) {
			String fn = "'%" + firstName + "%'";
			sb.append("AND a.firstName like " + fn);
		}
		if ( null != lastName && ! "".equals(lastName.trim())) {
			String ln = "'%" + lastName + "%'";
			sb.append(" AND a.lastName like " + ln);
		}
		List l = getHibernateTemplate().find(sb.toString());
		if ( l.size() > 0 ) {
			count = ( (Long) l.iterator().next()).intValue();
		}
		return count;
	}

	@SuppressWarnings("unchecked")
	public List<User> searchUser(String firstName, String lastName, int pageIndex, int pageSize) {
		Session session = getSession();
		StringBuffer sb = new StringBuffer();
		sb.append("FROM User a JOIN FETCH a.hospital WHERE 1 = 1 ");
		if ( null != firstName && ! "".equals(firstName.trim())) {
			String fn = "'%" + firstName + "%'";
			sb.append(" AND a.firstName like " + fn);
		}
		if ( null != lastName && ! "".equals(lastName.trim())) {
			String ln = "'%" + lastName + "%'";
			sb.append(" AND a.lastName like " + ln);
		}
		Query query = session.createQuery(sb.toString());
		query.setFirstResult((pageIndex - 1)*pageSize);
		query.setMaxResults(pageSize);
		return query.list();
	}

	@SuppressWarnings("unchecked")
	public User searchUserByUuid(String uuid) {
		//User user=(User)getHibernateTemplate().get(User.class, uuid);
		String hql = "FROM User u JOIN FETCH u.hospital WHERE u.uuid = ?";
		List<User> lu = getHibernateTemplate().find(hql, uuid);
		User u = null ;
		if ( lu.size() > 0 ) {
			u = lu.iterator().next();
		}
		return u;
	}

	public void saveAuthentication(User user, int[] authes) {
		user=(User) getHibernateTemplate().load(User.class,user.getUuid());
		user.setVerified(true);
		getHibernateTemplate().update(user);
		Authentication auth=new Authentication();
		auth.setUser(user);
		auth.setRole(authes[0]);
		auth.setResource(authes[1]);
		auth.setAuthority(authes[2]);
		getHibernateTemplate().saveOrUpdate(auth);
	}

	public void updateUser(String uuid,String fileName) {
		User user = (User) getHibernateTemplate().load(User.class, uuid);
		user.setPersonalPicture(fileName);
		getHibernateTemplate().saveOrUpdate(user);
	}

	@SuppressWarnings("unchecked")
	public User fetchUserByUsername(String username) {
		String hql = "FROM User WHERE username = ?" ;
		List<User> lu = getHibernateTemplate().find(hql,username);
		User u = null ;
		if ( lu.size() > 0 ) {
			u = lu.iterator().next();
		}
		return u ;
	}

	public void removeUser(String uuid) {
		Object user = getHibernateTemplate().load(User.class, uuid);
		getHibernateTemplate().delete(user);
	}

	public void updateUser(User user) {
		Session session = getSession();
		User u = (User) getHibernateTemplate().get(User.class, user.getUuid());
		u.setLastName(u.getLastName());
		if ( user.getPassword() != null && ! user.getPassword().trim().equals("")) {
			u.setPassword(user.getPassword());
		}
		u.setFirstName(u.getFirstName());
		u.setCellphone(user.getCellphone());
		u.setOfficeTel(user.getOfficeTel());
		u.setFamilyTel(user.getFamilyTel());
		u.setHospitalTel(user.getHospitalTel());
		u.setEmail(user.getEmail());
		u.setFax(user.getFax());
		u.setOfficeAddress(user.getOfficeAddress());
		u.setHomeAddress(user.getHomeAddress());
		u.setHospitalAddress(user.getHospitalAddress());
		u.setIntroduction(user.getIntroduction());
		getHibernateTemplate().update(u);
		
	}

}